package com.hengxinguotong.zhihuichengjian.ui.lift.data;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.LiftDataViolationListAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.LiftViolation;
import com.hengxinguotong.zhihuichengjian.bean.LiftViolationCount;
import com.hengxinguotong.zhihuichengjian.bean.LiftViolationCountRes;
import com.hengxinguotong.zhihuichengjian.customtimepicker.TimePickerActivity;
import com.hengxinguotong.zhihuichengjian.customtimepicker.bean.DayTimeEntity;
import com.hengxinguotong.zhihuichengjian.ui.lift.violation.LiftViolationDetailActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link LiftDataViolationFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 * 违章数据
 */
public class LiftDataViolationFragment extends BaseFragment implements View.OnClickListener, LiftDataViolationListAdapter.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String PARAM = "equipmentId";

    @BindView(R.id.search_date_tv)
    HXTextView searchDateTv;
    @BindView(R.id.violation_count_tv)
    HXTextView violationCountTv;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;
    @BindView(R.id.empty_img)
    ImageView emptyImg;

    private PullableRecyclerView dataRv;

    // TODO: Rename and change types of parameters
    private String equipmentId;
    private int pageIndex = 1;
    private String startTime,//开始时间 格式：2019-02-23
            endTime;//结束时间
    private List<LiftViolation> liftViolationList;
    private LiftDataViolationListAdapter liftDataViolationListAdapter;
    public LiftDataViolationFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param Parameter .
     * @return A new instance of fragment TowerDataLiveFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LiftDataViolationFragment newInstance(String param) {
        LiftDataViolationFragment fragment = new LiftDataViolationFragment();
        Bundle args = new Bundle();
        args.putString(PARAM, param);
        fragment.setArguments(args);
        return fragment;
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constants.UPDATE:
                    LiftViolationCount towerViolationCount = (LiftViolationCount) msg.obj;
                    List<LiftViolation> datas = towerViolationCount.getData();
                    bindData(datas);
                    violationCountTv.setText(towerViolationCount.getCount() + "次");
                    break;
            }
        }
    };

    private void bindData(List<LiftViolation> datas) {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            liftViolationList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            liftViolationList.addAll(datas);
        }
        showEmptyView(liftViolationList.size() == 0);
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        liftDataViolationListAdapter.setDataList(liftViolationList);
    }

    private void showEmptyView(boolean isEmpty){
        if(isEmpty){
            emptyImg.setVisibility(View.VISIBLE);
        }else {
            emptyImg.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            equipmentId = getArguments().getString(PARAM);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lift_data_violation, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    public void onLazyLoad() {
        processDate(new Date(), new Date());

    }

    private void initView() {
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        liftViolationList =  new ArrayList<>();
        liftDataViolationListAdapter = new LiftDataViolationListAdapter(getActivity(), liftViolationList);
        liftDataViolationListAdapter.setOnClickListener(this);
        dataRv.setAdapter(liftDataViolationListAdapter);
        dataRv.setItemAnimator(new DefaultItemAnimator());
        dataRv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = liftViolationList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getLiftViolationList("搜索中…");
            }
        }, 500);
    }

    public void getLiftViolationList(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(),"constructionid"));
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("equipmentId", equipmentId);//设备Id 获取某个塔吊设备的吊装循环数据、违章数据时必传，塔吊违章数据不需要传
            jsonObject.put("type", 1 + "");//0：正常；1：违章 只有获取违章数据、塔吊违章数据时传1，获取吊装循环数据不需要传
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/lift/getListWorkCycleData/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    LiftViolationCountRes res = gson.fromJson(json, LiftViolationCountRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.UPDATE;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                }else{
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    @OnClick({R.id.search_date_tv})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_date_tv:
                Intent intent = new Intent(getActivity(), TimePickerActivity.class);
                startActivityForResult(intent, 0);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == 0 && data != null){
                DayTimeEntity startDay = (DayTimeEntity) data.getSerializableExtra("startDay");
                DayTimeEntity stopDay = (DayTimeEntity) data.getSerializableExtra("stopDay");
                processDate(startDay, stopDay);
            }
        }
    }

    private void processDate(DayTimeEntity startDay, DayTimeEntity stopDay){
        startTime = dateFormat(startDay);
        endTime = dateFormat(stopDay);
        searchDateTv.setText(startTime  + " 至 " + endTime);
        initData();
    }

    private String dateFormat(DayTimeEntity dayTimeEntity){
        StringBuffer dateSb = new StringBuffer();
        dateSb.append(dayTimeEntity.getYear() + "-");
        if(dayTimeEntity.getMonth() > 9){
            dateSb.append(dayTimeEntity.getMonth() + "-");
        }else {
            dateSb.append( "0" + dayTimeEntity.getMonth() + "-");
        }
        if(dayTimeEntity.getDay() > 9){
            dateSb.append(dayTimeEntity.getDay());
        }else {
            dateSb.append( "0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    private void processDate(Date startdate, Date enddate){
        startTime = dateFormat(startdate);
        endTime = dateFormat(enddate);
        searchDateTv.setText(startTime  + " 至 " + endTime);
        initData();
    }

    private String dateFormat(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    @Override
    public void onClick(Object o) {
        LiftViolation liftViolation = (LiftViolation) o;
        if(liftViolation == null){
            return;
        }
        Intent intent = new Intent(getActivity(), LiftViolationDetailActivity.class);
        intent.putExtra("liftViolation", liftViolation);
        startActivity(intent);
    }
}
